package com.zjn.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zjn.pojo.Page;
import com.zjn.pojo.Role;
import com.zjn.pojo.User;
import com.zjn.service.RoleService;
import com.zjn.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@ResponseBody
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    /*显示用户页面*/
    @GetMapping("/user/list")
    public ModelAndView userList(@RequestParam(required = false, defaultValue = "1", value = "pageNum") Integer pageNum,
                                 @RequestParam(defaultValue = "8", value = "pageSize") Integer pageSize,
                                 HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();
        //为了程序的严谨性，判断非空：
        if (pageNum == null || pageNum <= 0) {
            pageNum = 1;   //设置默认当前页
        }
        if (pageSize == null) {
            pageSize = 5;    //设置默认每页显示的数据数
        }

        //从前端获取参数
        String userName = request.getParameter("queryName");
        String queryUserRole = request.getParameter("queryUserRole");
        if (userName == ""){
            userName = null;
        }
        if (queryUserRole == null){
            queryUserRole = "0";
        }
        //将查询需要的参数存入map中
        Map<String, Object> map = new HashMap<>();
        map.put("userName", userName);
        map.put("userRole", Integer.parseInt(queryUserRole));

        //1.引入分页插件,pageNum是第几页，pageSize是每页显示多少条,默认查询总数count
        PageHelper.startPage(pageNum, pageSize);

        //2.紧跟的查询就是一个分页查询-必须紧跟.后面的其他查询不会被分页，除非再次调用PageHelper.startPage
        try {
            List<User> userList = userService.getUserList(map);
            //为每个对象查出对应的权限名
            for (User user : userList) {
                Role role = new Role();
                role.setId(user.getUserRole());
                String roleName = roleService.getRoleByRole(role).getRoleName();
                user.setUserRoleName(roleName);
            }
            //3.使用PageInfo包装查询后的结果,5是连续显示的条数,结果list类型是Page<E>
            PageInfo<User> pageInfo = new PageInfo<User>(userList, pageSize);

            //4.使用modelAndView将数据带回前端
            mav.addObject("pageInfo", pageInfo);
        } finally {
            PageHelper.clearPage(); //清理 ThreadLocal 存储的分页参数,保证线程安全
        }
        //获取权限名并传入前端
        List<Role> roleList = roleService.getRoleList();
        mav.addObject("roleList", roleList);
        //将查询表中的参数返回，以增加用户的体验性
        mav.addObject("queryName", userName);
        mav.addObject("queryUserRole", Integer.parseInt(queryUserRole));

        mav.setViewName("user/UserList");
        return mav;
    }

    /*跳转到员工添加*/
    @GetMapping("/user/userAdd")
    public ModelAndView toUserAdd() {
        ModelAndView mav = new ModelAndView();
        List<Role> roleList = roleService.getRoleList();
        mav.addObject("roleList", roleList);
        mav.setViewName("user/UserAdd");
        return mav;
    }

    /*员工添加*/
    @PostMapping("/user/userAdd")
    @ResponseBody
    public ModelAndView userAdd(User user, HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mav = new ModelAndView();
        String method = request.getParameter("method");
        System.out.println(method);
        //当method为add时，代表全部输入合法，成功添加
        if (method.equals("add") && method != null) {
            String birthday = request.getParameter("birthday");
            try {
                user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            user.setCreationDate(new Date());
            //获取当前用户
            Subject subject = SecurityUtils.getSubject();
            //封装用户的登录数据，这里的token是全局变量，可以在任意位置取出
            User currentUser = (User) subject.getPrincipal();
            user.setCreatedBy(currentUser.getId());
            int flag = 0;
            flag = userService.userAdd(user);
            if (flag > 0) {
                mav.setViewName("redirect:/user/list");
            } else {
                mav.setViewName("/user/UserAdd");
            }
        }
        //ajax动态获取角色选择栏参数
        else if (method.equals("getrolelist") && method != null) {
            List<Role> roleList = roleService.getRoleList();
            try {
                //将roleList转换成json对象
                response.setContentType("application/json;charset=utf-8");
                PrintWriter writer = response.getWriter();
                writer.write(JSONArray.toJSONString(roleList));
                writer.flush();
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //ajax动态验证登录账号userCode是否已经存在
        else if (method.equals("ucexist") && method != null) {
            //判断用户账号是否可用
            String userCode = request.getParameter("userCode");
            //用于存放对userCode判断对结果
            Map<String, String> resultMap = new HashMap<String, String>();
            //判断userCode是否为空
            if (userCode == null || ("").equals(userCode)) {
                //userCode == null || userCode.equals("")
                resultMap.put("userCode", "null");
            } else {
                User user1 = new User();
                user1.setUserCode(userCode);
                user1 = userService.queryUserByUser(user1);
                if (null != user1) {
                    resultMap.put("userCode", "exist");
                } else {
                    resultMap.put("userCode", "notexist");
                }
            }
            try {
                //把resultMap转为json字符串以json的形式输出
                //配置上下文的输出类型
                response.setContentType("application/json");
                //从response对象中获取往外输出的writer对象
                PrintWriter outPrintWriter = response.getWriter();
                //把resultMap转为json字符串 输出
                outPrintWriter.write(JSONArray.toJSONString(resultMap));
                outPrintWriter.flush();//刷新
                outPrintWriter.close();//关闭流
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return mav;
    }

    /*删除员工*/
    @GetMapping("/user/userDelete")
    @ResponseBody
    public ModelAndView userDelete(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mav = new ModelAndView();
        String id = request.getParameter("code");
        Map<String, String> resultMap = new HashMap<String, String>();
        int flag = userService.deleteUserById(Integer.parseInt(id));
        if (flag > 0) {
//            mav.setViewName("redirect:/user/list");
            resultMap.put("code", "success");
        } else {
//            mav.setViewName("redirect:/user/list");
            resultMap.put("code", "error");
        }
        try {
            //把resultMap转为json字符串以json的形式输出
            //配置上下文的输出类型
            response.setContentType("application/json");
            //从response对象中获取往外输出的writer对象
            PrintWriter outPrintWriter = response.getWriter();
            //把resultMap转为json字符串 输出
            outPrintWriter.write(JSONArray.toJSONString(resultMap));
            outPrintWriter.flush();//刷新
            outPrintWriter.close();//关闭流
        } catch (IOException e) {
            e.printStackTrace();
        }
        mav.setViewName("redirect:/user/list");
        return mav;
    }

    /*跳转到员工修改*/
    @GetMapping("/user/userUpdate/{id}")
    public ModelAndView toUserUpdate(@PathVariable("id") int id) {
        ModelAndView mav = new ModelAndView();
        List<Role> roleList = roleService.getRoleList();
        User user = new User();
        user.setId(id);
        user = userService.queryUserByUser(user);
        mav.addObject("roleList", roleList);
        mav.addObject("user", user);
        mav.setViewName("user/UserUpdate");
        return mav;
    }

    /*员工修改*/
    @PostMapping("/user/userUpdate")
    public ModelAndView userUpdate(User user) {
        ModelAndView mav = new ModelAndView();
        int flag = userService.modifyUserById(user);
        if (flag > 0) {
            mav.setViewName("redirect:/user/list");
        } else {
            mav.setViewName("redirect:/user/userUpdate");
        }
        return mav;
    }

    /*员工查看*/
    @GetMapping("/user/userView/{id}")
    public ModelAndView userView(@PathVariable("id") int id) {
        ModelAndView mav = new ModelAndView();
        User user = new User();
        user.setId(id);
        user = userService.queryUserByUser(user);
        Role role = new Role();
        role.setId(user.getUserRole());
        String roleName = roleService.getRoleByRole(role).getRoleName();
        user.setUserRoleName(roleName);
        mav.addObject("user", user);
        mav.setViewName("user/UserView");
        return mav;
    }


}
